package com.timecheck.util;

import org.apache.http.HttpEntity;
import org.apache.http.HttpHeaders;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import java.nio.charset.StandardCharsets;

public class HttpClientUtil {
    public static String httpPost(String url, String message){
        //创建httppost对象
        HttpPost post = new HttpPost(url);
        StringEntity stringEntity = new StringEntity(message, StandardCharsets.UTF_8);

        //请求参数
        post.setEntity(stringEntity);

        //请求头
        post.setHeader("Content-Type", "application/json;charset=UTF-8");
        // 返回信息
        String msg = "";
        try {

            //设置长/短连接 此处为短连接
            post.setHeader(HttpHeaders.CONNECTION, HTTP.CONN_CLOSE);

            //创建httpclient对象发送post请求
            CloseableHttpClient httpClient = HttpClients.createDefault();
            CloseableHttpResponse resp = httpClient.execute(post);

            try {

                //返回信息
                HttpEntity entity = resp.getEntity();

                if (entity != null) {
                    msg = EntityUtils.toString(entity);
                }else {
                    msg = "结果为null";
                }

            } finally {
                resp.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
            msg = "调用接口异常\n" + e.getMessage();
            return msg;
        } finally {
            post.reset();
            post.releaseConnection();
        }
        return msg;
    }
}
